﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using Cofe.Core;

namespace Cofe.Web
{
    //http://www.pieterg.com/2012/2/coffeescript-custom-processor-in-aspnet-mvc-4
    public class CoffeeCompiler : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            var coffeeScriptEngine = new CoffeeSharp.CoffeeScriptEngine();
            string compiledCoffeeScript = String.Empty;
            foreach (var file in response.Files.OrderBy(f => f.Name))
            {
                try
                {
                    using (var reader = new StreamReader(file.FullName))
                    {

                        compiledCoffeeScript += coffeeScriptEngine.Compile(reader.ReadToEnd());
                        reader.Close();
                    }
                }
                catch (Exception ex)
                {
                    CofeServices.Logger.Log(ex);
                    throw new HttpParseException("Failed when processing " + file.FullName, ex);
                }
            }
            response.Content = compiledCoffeeScript;
            response.ContentType = "text/javascript";
            response.Cacheability = HttpCacheability.Public;
        }
    }
}